<template>
	<view class="content" >
		
			<u-navbar :is-back="true" :border-bottom="false">
				<view style="height: 10px;"></view>
				<view  class="slot-wrap disfr-lr p15 f32" style="width: 100%;">
					<view class="slot-wrap-left"></view>
					<view class="slot-wrap-center mt10">商机详情</view>
					<view class="slot-wrap-right pr">
						<view v-if="result.user_id == $vuex.state.globalData.user.user_id" @click="goPage" :data-uri="'/pages/business-topup/business-topup?opportunity_id='+result.id" style="position: relative;top:-0rpx;right:5px;">
							<view class="custom-min-button" style="border-radius: 4px;">推荐置顶</view>
						</view>
					</view>
				</view>
			</u-navbar>

			<view v-if="show_main" class="main" >
				<view class="bgf" style="height: 10rpx;"></view>
			    <view class="bgf p30 pr" style="padding-bottom: 20rpx;">
					<view class="b f32 disf">
						<text>{{result.title}}</text>
						<view v-if="result.coin_orders > 0 || result.orders > 0" class="bgf" style="width: 38rpx;height: 38rpx;position: absolute;top:30rpx;right:30rpx;overflow: hidden;">
						   <u-icon name="zhiding1" custom-prefix="qxl-icon" color="#2979ff" size="40"></u-icon>
					    </view>
					</view>
					<view class="disf mt10 pb20">
						<!--<view style="width: 46rpx;height: 46rpx;overflow: hidden;border-radius:4px;flex-shrink: 0;">
							<u-image width="48rpx" height="48rpx" :src="result.head_pic">
								<template v-slot:error>
									<image src="/static/image/default-user.png" style="width:48rpx;height: 48rpx;"></image>
								</template>
							</u-image>
						</view>-->
						<view class="ml10 disfr-lr" style="top:0rpx;width: 100%;">
							<!--<view class="toell" style="width: 280rpx;">{{result.nickname}}</view>-->
							<view class="col999 f28">{{result.add_time_str}}</view>
						</view>
					</view>
					<view class="disfr-lr pb20">
						<view class="f30 pr" style="top:12rpx;color:#666666">
							<u-tag :text="result.classify_name" type="primary" mode="light"
							style="margin-left: 5rpx;position: relative;top:-5rpx;"/>
						</view>
						<view class="f28 col999">
							合作区域:{{result.area}}
						</view>
					</view>
					<view class="details bto pv20">
						<view v-for="(item,index) in result.tag_text" :key="item.id" :class="'f32 disf '+(index > 0 ? 'mt20' : 'mt10')">
							<view style="flex-shrink: 0;">{{item.title}}:</view>
							<view class="ml10 pr" style="top:-5rpx;">
								<u-tag v-for="(item2,index2) in item.item" :key="index2" :text="item2" type="primary" size="mini" mode="dark" style="margin-right: 10rpx;"/>
							</view>
						</view>
						
						<view class="mt20 f32" style="line-height: 180%;">
							<rich-text :nodes="result.content"></rich-text>
							<!--<u-parse :content="result.content" @navigate="navigate"></u-parse>-->
						</view>
						<view v-if="result.images" class="images mt20 disf" style="flex-wrap: wrap;">
							
							<image v-for="(item,index) in result.images" :key="index" :src="item" 
							@click="previewImage" :data-index="index"
							style="height: 145rpx;flex-shrink: 0;margin-right: 10rpx;margin-top: 10px;" mode="heightFix"></image>
						</view>
					</view>
					<view class="disfr-lr bto pt20">
						<view class="col999">
							<u-icon name="eye-fill" size="52" style="position: relative;top:5rpx;color:#999"></u-icon>{{result.page_view}}
						</view>
						<view v-if="result.is_collect" @click="setcollect" class="f26" style="color:#2979ff">
							<u-icon name="a-31guanzhu1-xuanzhong" custom-prefix="qxl-icon" 
							size="40" style="position: relative;top:5rpx;"></u-icon>收藏
						</view>
						<view v-else @click="setcollect" class="f26 col999">
							<u-icon name="a-31guanzhu1-xuanzhong" custom-prefix="qxl-icon" 
							size="40" style="position: relative;top:5rpx;"></u-icon>收藏
						</view>
					</view>
				</view>
				<view class="f32 p30">留言</view>
				<view v-if="autoreView.length > 0" class="bgf pv20">
					<view v-for="(item,index) in autoreView" 
					@click="sendUserInfo" :data-user_id="item.user_id" :data-is_private_chat="item.is_private_chat"
					:class="'disf f30 p30 '+(index < autoreView.length-1 ? 'bbo' : '')">
						<view style="width: 80rpx;height: 80rpx;overflow: hidden;border-radius:50%;flex-shrink: 0;">
							<u-image width="80rpx" height="80rpx" :src="item.user_head_pic">
								<template v-slot:error>
									<image src="/static/image/default-user.png" style="width:80rpx;height: 80rpx;"></image>
								</template>
							</u-image>
						</view>
						<view class="ml10" style="width: 100%;">
							<view class="disfr-lr">
								<view>{{item.user_nickname}}</view>
								<view class="col999">{{item.critique_time_str}}</view>
							</view>
							<view class="col999">已查看，点我头像可私聊</view>
							
							<view v-if="item.reply.is_private_chat" class="mt10 p20" style="background: #f4f4f4;color:#666;border-radius: 6px;">
								<view>
									<text>{{item.reply.user_nickname}}</text>
									<u-tag text="发布人" type="primary" size="mini" style="margin-left: 5rpx;border:none;background: #2979ff;color:#fff;position: relative;top:-5rpx;"/>
								</view>
							    <view class="mt10">合作已私聊<!--{{item.reply.content}}--></view>
							</view>
						</view>
					</view>
				</view>
				<view v-else style="text-align: center;margin-top: 20%;">
					<view><u-icon name="wuneirong-copy" custom-prefix="qxl-icon" color="#999999" size="100"></u-icon></view>
					<view class="f32 col999 mt20">暂无用户留言</view>
				</view>
				<pageload :page_load="page_load" :next_page="next_page" :list="autoreView" /><!--分页加载状态-->
				<!--底部联系它-->
				<view v-if="result.user_id != result.login_user_id">
					<view style="height: 100rpx;"></view>
					<view class="pf pfid-bottom">
						<button @click="privateChat" class="my_button">联系TA</button>
					</view>
				</view>
			</view>
		
		<loading :loading="not_load"/><!--加载状态-->
		
	</view>
</template>

<script setup>
//import uParse from '@/components/u-parse/u-parse.vue'
import { onLoad, onShow, onHide, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
import { ref } from 'vue';	
const show_main=ref(false);
const page_load=ref(false);
const not_load=ref(false);
const next_page=ref('');
const result=ref({});
const opportunity_id=ref('');
const getParam=ref({});
const navigate=(url)=>{
	plus.runtime.openURL(url, function(e) {
	        //console.log('打开URL成功');
	}, function(e) {
	        //console.log('打开URL失败: ' + e.message);
	});
};
//私聊发布者
const privateChat=async()=>{
	if(!not_load.value) return;
	let userId=result.value.user_id;
	let opportunity_id=result.value.id;
	let conv=getConversationID(userId);
	let uri='';
	//聊天卡片
	let card='{"type":"card","id":'+result.value.id+',"title":"'+result.value.title+'","cate_name":"'+result.value.classify_name+'","author":"'+result.value.nickname+'","author_img":"'+result.value.head_pic+'"}';
	// 置顶的不需要消耗虚拟币
	if(result.value.coin_orders > 0){
		if(conv.conversationID){
			uri='/pages/chat-single/chat-single?conversationID='+conv.conversationID+'&nick='+conv.userProfile.nick+'&to='+userId+'&opportunity_id='+opportunity_id;
			uni.$utils.goPage(uri,0);
		}else{
			not_load.value=false;
			let str=uni.$appConfig['IM_PREFIX_MAKR']['da_zhao_hu']['rule']+'你好！';
			uni.TIM.createTextMessage(0,userId,str,(data)=>{
				// 标记合作已私聊
				let currentUserId=uni.$vuex.state.globalData.user.user_id;
				uni.$get('/appapi-opportunity-markchat',{opportunity_id:result.value.id,user_id:currentUserId});
				setTimeout(()=>{
					conv=getConversationID(userId);
					//console.log(conv);
					not_load.value=true;
					if(conv.conversationID){
						uri='/pages/chat-single/chat-single?conversationID='+conv.conversationID+'&nick='+conv.userProfile.nick+'&to='+userId+'&opportunity_id='+opportunity_id;
						uni.$utils.goPage(uri,0);
						return;
					}
					uni.$utils.showToast('消息发送成功');
				},500)
			},card);
		}
		return;
	}
	
	//非置顶处理罗辑
	if(conv.conversationID && result.value.current_is_chat > 0){
		uri='/pages/chat-single/chat-single?conversationID='+conv.conversationID+'&nick='+conv.userProfile.nick+'&to='+userId+'&opportunity_id='+opportunity_id;
		uni.$utils.goPage(uri,0);
		return;
	}else if(result.value.current_is_chat > 0){
		not_load.value=false;
		let str=uni.$appConfig['IM_PREFIX_MAKR']['da_zhao_hu']['rule']+'你好！';
		uni.TIM.createTextMessage(0,userId,str,(data)=>{
			// 标记合作已私聊
			//let currentUserId=uni.$vuex.state.globalData.user.user_id;
			//uni.$get('/appapi-opportunity-markchat',{opportunity_id:result.value.id,user_id:currentUserId});
			setTimeout(()=>{
				conv=getConversationID(userId);
				//console.log(conv);
				not_load.value=true;
				if(conv.conversationID){
					uri='/pages/chat-single/chat-single?conversationID='+conv.conversationID+'&nick='+conv.userProfile.nick+'&to='+userId+'&opportunity_id='+opportunity_id;
					uni.$utils.goPage(uri,0);
					return;
				}
				uni.$utils.showToast('消息发送成功');
			},500)
		},card);
		return;
	}
	uni.$utils.showModal('私聊需要消耗'+result.value.chat_coin_num+'个('+result.value.virtual_coin_name+')当天有效，是否继续？',1,async()=>{
		//console.log(conv);return;
		not_load.value=false;
		//扣私聊币
		let status=await privateTrade();
		if(status !== true){
			uni.$utils.showToast(status);
			not_load.value=true;
			return;
		}
		result.value.current_is_chat=1;
		let str=uni.$appConfig['IM_PREFIX_MAKR']['da_zhao_hu']['rule']+'你好！';
		uni.TIM.createTextMessage(0,userId,str,(data)=>{
			// 标记合作已私聊
			let currentUserId=uni.$vuex.state.globalData.user.user_id;
			uni.$get('/appapi-opportunity-markchat',{opportunity_id:result.value.id,user_id:currentUserId});
			setTimeout(()=>{
				conv=getConversationID(userId);
				console.log(conv);
				not_load.value=true;
				if(conv.conversationID){
					uri='/pages/chat-single/chat-single?conversationID='+conv.conversationID+'&nick='+conv.userProfile.nick+'&to='+userId+'&opportunity_id='+opportunity_id;
					uni.$utils.goPage(uri,0);
					return;
				}
				uni.$utils.showToast('消息发送成功');
			},500)
		},card);
	});
	
};
// 发送留言者信息
const sendUserInfo=async(e)=>{
	if(!not_load.value) return;
	let uri='';
	if(result.value.user_id != result.value.login_user_id) return; // 不是作者不能给留言的用户发消息
	let is_private_chat=e.currentTarget.dataset.is_private_chat;
	let userId=e.currentTarget.dataset.user_id;
	let conv=getConversationID(userId);
    if(conv.conversationID && result.value.current_is_chat > 0){
		uri='/pages/chat-single/chat-single?conversationID='+conv.conversationID+'&nick='+conv.userProfile.nick+'&to='+userId;
		uni.$utils.goPage(uri,0);
		return;
	}else{
		let str=uni.$appConfig['IM_PREFIX_MAKR']['da_zhao_hu']['rule']+'你好！';
		uni.TIM.createTextMessage(0,userId,str,(data)=>{
			setTimeout(()=>{
				//标记合作已私聊
				if(!result.value.is_private_chat) uni.$get('/appapi-opportunity-markchat',{opportunity_id:result.value.id,user_id:userId});
				conv=getConversationID(userId);
				//console.log(conv);
				not_load.value=true;
				if(conv.conversationID){
					uri='/pages/chat-single/chat-single?conversationID='+conv.conversationID+'&nick='+conv.userProfile.nick+'&to='+userId;
					uni.$utils.goPage(uri,0);
					return;6
				}
				uni.$utils.showToast('消息发送成功');
			},500)
		});
		return;
	}
	/*uni.$utils.showModal('私聊需要消耗'+result.value.chat_coin_num+'个'+result.value.virtual_coin_name+'当天有效，是否继续？',1,async()=>{
		//console.log(conv);return;
		not_load.value=false;
		//扣私聊币
		let status=await privateTrade();
		if(status !== true){
			uni.$utils.showToast(status);
			not_load.value=true;
			return;
		}
		result.value.current_is_chat=1;
		let str=uni.$appConfig['IM_PREFIX_MAKR']['da_zhao_hu']['rule']+'你好！';
		uni.TIM.createTextMessage(0,userId,str,(data)=>{
			setTimeout(()=>{
				//标记合作已私聊
				if(!result.value.is_private_chat) uni.$get('/appapi-opportunity-markchat',{opportunity_id:result.value.id,user_id:userId});
				conv=getConversationID(userId);
				console.log(conv);
				not_load.value=true;
				if(conv.conversationID){
					uri='/pages/chat-single/chat-single?conversationID='+conv.conversationID+'&nick='+conv.userProfile.nick+'&to='+userId;
					uni.$utils.goPage(uri,0);
					return;
				}
				uni.$utils.showToast('消息发送成功');
			},2000)
		});
	});*/
	
};

// 私聊扣币
const privateTrade=async()=>{
	let get={opportunity_id:result.value.id};
	let ret = await uni.$get('/appapi-opportunity-privatetrade',get);
	if(ret.error_code != 0) return ret.info;
	return true;
};
//获取当前用户的会话ID
const getConversationID=(userId)=>{
	let list=uni.$vuex.state.globalData.conversationList;
	for(let i in list){
		if(list[i].type != 'C2C') continue;
		if(list[i].userProfile.userID == userId){
			return list[i];
		}
	}
	return {};
};
//收藏
const setcollect=async()=>{
	let ret = await uni.$get('/appapi-opportunity-setcollect',{id:result.value.id});
	if(ret.error_code != 0){
		uni.$utils.showToast(ret.info,0,()=>{
		});
		return;
	}
	if(ret.data.type == -1){
		uni.$utils.showToast('操作过于频繁，请稍后再试',0,()=>{
		});
		return;
	}
	if(ret.data.type == 1) result.value.is_collect=true;
	else result.value.is_collect=false;
};
// 查看图片
const previewImage =  (e)=> {
	let arr=result.value.images;
    var index = parseInt(e.currentTarget.dataset.index);
	 var current = arr[index];
    wx.previewImage({
       current: current, // 当前显示图片的http链接  
       urls: arr // 需要预览的图片http链接列表  
   })
};
//页面加载时
onLoad(async (options)=>{
	opportunity_id.value=options.id;
	getParam.value=options;
    
});
//页面显示时执行
onShow(()=>{
	//console.log('语法糖onShow');
	loadPage(getParam.value,false);
});
//页面隐藏时执行
onHide(()=>{
	//console.log('语法糖onHide');
});
/**
 * 加载接口数据
 * @param {Object} options  参数,对像数组
 * @param {Object} isPage   是否加载大于1页
 */
const loadPage=async (options,isPage)=>{
	let ret = await uni.$get('/appapi-opportunity-details',options);
	if(ret.error_code != 0){
		uni.$utils.showToast(ret.info,0,()=>{
			uni.navigateBack({data:1});
		});
		return;
	}
	//console.log(options);\n\r
	ret.data.content=ret.data.content.replace(/\n\r/g,'<br/>');
	//console.log(ret.data);
	show_main.value=true;
	not_load.value=true;
	result.value=ret.data;
	getAutoreView({});
	console.log(result.value);
};
// 获取留言
const autoreView=ref([]);
const getAutoreView=async (get)=>{
	get.opportunity_id=opportunity_id.value;
	let ret = await uni.$get('/appapi-opportunity-getautoreview',get);
	console.log(ret.data);
	page_load.value=false;
	if(ret.error_code != 0){
		uni.$utils.showToast(ret.info,0,()=>{
			//uni.navigateBack({data:1});
		});
		return;
	}
	next_page.value=ret.data.next_page;
	if(autoreView.value.length > 0){
		autoreView.value=[...autoreView.value,...ret.data.list];
	}else{
		autoreView.value=ret.data.list;
	}
	
	//console.log('getAutoreView',ret.data);
};
//上拉触底加载分页
onReachBottom(()=>{
	if (!next_page.value) return;
	if (page_load.value) return;
	page_load.value=true;
	setTimeout(()=>{
	  getAutoreView(next_page.value, true); 
	},2000);
});
/**
 * 模板属性跳转页面
 * @param {Object} e
 */
function goPage(event){
	uni.$utils.dataSetPage(event);
};

</script>

<style  lang="scss">
	/*@import url("@/components/u-parse/u-parse.css");*/
	page {
		
	}
	.pfid-bottom{
		bottom:0;
		left:0;
		width: 100%;
		height: 100rpx;
		border-top:0.5rpx solid #ccc;
		background: #fff;
		text-align: center;
	}
	.my_button{
		color:#fff;
		font-weight: normal;
		font-size: 28rpx;
		border:none;
		background: blue;
		background: #2979ff;
		display: inline-block;
		width: 400rpx;
		margin-top: 20rpx;
	}
</style>
